
/*
* 贷后管理首页 台账 js
*
* */
var layer;
var table;
var basePath;
var vm;
window.layinit(function (htConfig) {
    var _htConfig = htConfig;
    basePath = _htConfig.coreBasePath;
    uiBasePath = _htConfig.uiBasePath;
    vm = new Vue({
        el: '#app',
        data: {
            loading: false,
            searchForm: {
                tableName: ''  //发薪时间
            },
            // 文件上传
            uploadSalaryModel:false,
            uploadSalarySetForm:{
                timeYearMonth:'',
                uploadType: '',
                templateCode:'',
                uploadSalaryFile:null,
                salaryFileType:''
            },
            templateList:[],
            userName:'',
            userId:'',
            uploadSalarySetFormValidate:{
                timeYearMonth: [
                    { required: true, message: '请选择时间'},
                ],
                templateCode: [
                    { required: true, message: '请选择模板'},
                ],
                uploadType: [
                    { required: true, message: '请选择导入方式'},
                ],
                uploadSalaryFile: [
                    { required: true, message: '请选择导入文件'},
                ]
            }

        },

        methods: {
            //重载表格
            toLoading: function () {
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                table.reload('listTable', {
                    where: {

                        tableName: self.searchForm.tableName //
                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },
            handleReset: function (name) { // 重置表单
                vm.searchForm.trailerStartDate = '';
                vm.searchForm.trailerEndDate = '';

                vm.searchForm.status = '';
                //var a=$("#trailerStartDate");
                //console.log(a);
                //alert(JSON.stringify(a));
                var tt = this.$refs[name];
                tt.resetFields();
                vm.toLoading();
            },
            ////  ----   单行操作界面显示  结束 -----------------
            clickExport: function () {//导出Excel表格

            },
            init: function () {
                var self = this;

                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    config = layui.ht_config;
                    //执行渲染
                    table.render({
                        elem: '#listTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'listTable'

                        , cols: [[
                            {type:'checkbox'}
                            ,{field:'fileCode', title: '上传批次号',align: 'center'}
                            ,{field:'fileName', title: '表格名称',align: 'center'}
                            ,{field:'time', title: '时间', sort: true,align: 'center'}

                            ,{field:'succesNumber', title: '成功行数', align: 'center'}
                            ,{field:'faileNumber', title: '失败行数',align: 'center'}
                            ,{field:'state', title: '审核状态',align: 'center',templet:"#checkState"}

                            ,{field:'importUserName', title: '上传人',align: 'center'}
                            ,{field:'lastUpdateTime', title: '上传时间',align: 'center'}
                            ,{fixed:'right',title: '操作', width: 170, align: 'center',toolbar:'#barTools'}
                        ]], //设置表头
                        url: basePath + 'dataImport/list',

                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            self.loading = false;
                            $.get(config.loadSelfinfoUrl, null, function (result) {
                                //表单数据填充
                                if (result.result) {
                                    self.userName = result.result.userName;
                                	self.userId = result.result.userId;
                                };
                            });
                        }
                    });
                    table.on('tool(listTable)', function (obj) {
                        var selectedRowInfo = obj.data;
                        if(obj.event === 'delete'){
                            layer.confirm('真的删除么?', function(index){
                                self.deleteImportData(selectedRowInfo.fileId,selectedRowInfo.batchCode);
                                layer.close(index);
                            });

                        }
                        if(obj.event === 'info'){
                            var templateCode = selectedRowInfo.templateCode;
                            var fileId = selectedRowInfo.fileId;
                            var batchCode = selectedRowInfo.batchCode;
                            self.showDataInfo(templateCode,fileId,batchCode);
                        }
                        if(obj.event === 'dataCheck'){
                            var failCount = selectedRowInfo.faileNumber;
                            if(selectedRowInfo.state == 1){
                                self.$Modal.error({content: '该批次数据已审核'});
                                return;
                            }
                            if(failCount>0){
                                self.$Modal.error({content: '存在未修正的数据：' + failCount+'条'});
                            }else{
                                layer.confirm('本批次总共：'+selectedRowInfo.succesNumber+"条数据", {
                                    btn: ['确认','取消'] //按钮
                                }, function(index){
                                    self.dataCheck(selectedRowInfo.fileId,selectedRowInfo.batchCode,selectedRowInfo.templateCode);
                                    layer.close(index);
                                });
                            }

                        }

                    });
                })
            },
            showDataInfo:function (templateCode,fileId,batchCode) {
                var  url = "/importLog/info?templateCode="+templateCode+"&fileId="+fileId+"&batchCode="+batchCode;
                var tile = "导入数据详情";
                var openIndex= layer.open({
                    type: 2,
                    area: ['80%', '80%'],
                    fixed: false,
                    maxmin: true,
                    title:tile,
                    content: url
                });
            },
            deleteImportData:function (fileId,batchCode) {
                var self = this;
                // 获取薪资模板列表
                var url = basePath + "dataImport/delete?fileId="+fileId+"&batchCode="+batchCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            layer.msg("删除成功");
                        }else{
                            self.$Modal.error({content: '调用接口失败：' + result.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        self.$Modal.error({content: '消息：' + data});
                        self.toLoading();
                    }

                });
            },
            // 导入数据
            uploadInitData:function () {
                var self = this;
                self.uploadSalaryModel = true;

                var self = this;
                // 获取薪资模板列表
                var url = basePath + "salaryTemplate/getTemplateListByType";
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0000") {
                            console.log('模板列表', result.data);
                            self.templateList = result.data;
                        }else{
                            self.$Modal.error({content: '调用接口失败：' + result.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        self.$Modal.error({content: '消息：' + data});
                        self.toLoading();
                    }

                });

                self.uploadSalaryModel = true;
                self.uploadSalarySetForm.timeYearMonth = '';
                self.uploadSalarySetForm.uploadType = '';
                self.uploadSalarySetForm.templateCode = '';
            },
            // 获取上传工资文件对象
            beforeUpLoadFile: function (file) {
                console.log("上传前的文件：" ,  file)
                this.$refs.upload.clearFiles();
                this.uploadSalarySetForm.uploadSalaryFile = file;
            },
            // 关闭工资表上传窗口
            closeUploadSalaryModal:function(){
                this.uploadSalaryModel = false
                this.$refs['uploadSalarySetForm'].resetFields();
                this.uploadSalarySetForm.uploadSalaryFile = null;
                this.$refs.upload.clearFiles();
            },
            
            // 移除文件的方法
            removeFile:function(file, fileList){
            	 this.uploadSalarySetForm.uploadSalaryFile = null;
            },
            // 提交上传工资表前验证
            beforeUpload: function(){
                var self = this;
                var validateFlag = false;
                self.$refs["uploadSalarySetForm"].validate(function (valid){
                    if (valid) {
                        validateFlag = true;
                    }
                });
                if(!validateFlag){
                    return false;
                }
                if(!self.uploadSalarySetForm.uploadSalaryFile){
                    this.$Message.error('请选择上传文件！');
                    return false;
                }

                // 校验操作
                var url = basePath + "salaryExcel/validateUpload";
                var data = {
                    uploadType:self.uploadSalarySetForm.uploadType,
                    timeYearMonth:self.uploadSalarySetForm.timeYearMonth,
                    templateCode:self.uploadSalarySetForm.templateCode,
                };
                $.ajax({
                    type: "POST",
                    url: url ,
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0000") {
                            self.submitUpload();
                        }else{
                            self.$Modal.error({content: '消息：' + result.msg});
                        }
                        self.toLoading();
                    },
                    error:function (data) {
                        self.$Modal.error({content: '消息：' + data});
                        self.toLoading();
                    }

                });

            },

            // 上传
            submitUpload:function(){
                var self = this;

                var loadingIndex = layer.load();
                var url = basePath + "salaryExcel/uploadSalaryFile";
                var formData = new FormData();
                console.log("提交：", self.uploadSalarySetForm.uploadSalaryFile);
                formData.append('file', self.uploadSalarySetForm.uploadSalaryFile);
                formData.append('uploadType', self.uploadSalarySetForm.uploadType);
                formData.append('timeYearMonth', self.uploadSalarySetForm.timeYearMonth);
                formData.append('salaryFileType', self.uploadSalarySetForm.salaryFileType);
                formData.append('templateCode', self.uploadSalarySetForm.templateCode);
                console.log("=============", self.userName, self.userId);
                formData.append('userName', self.userName);
                formData.append('userId', self.userId);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data.returnCode == "0000") {
                        	self.processImport(loadingIndex, data.data);
                        }else{
                        	layer.close(loadingIndex);
                            self.$Modal.error({content: '消息：' + data.msg});
                            self.toLoading();
                        }
                    },
                    error:function (data) {
                        layer.close(loadingIndex);
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoading();
                    }
                });
            },
            
            // 轮询请求后台
            processImport: function(loadingIndex, processCode){
                var self = this;
                
                var url = basePath + "salaryExcel/getUploadSalaryFileState?processCode=" + processCode;
                // 轮询
                var interval = setInterval(function(){
                    $.ajax({
                    	  type: "GET",
                          url: url ,
                          contentType: "application/json; charset=utf-8",
                          async: false,
                          dataType: "json",
		                  success:function(data){
		                	    console.log("轮询结果", data);
			                    if (data.returnCode == "0000") {
		                    		 layer.close(loadingIndex);
		                             self.toLoading();
		                             self.uploadSalaryModel = false;
		                             self.$refs.upload.clearFiles();
		                             self.uploadSalarySetForm.uploadSalaryFile = null;
		                             // 轮询结束
		                             clearInterval(interval);
		                             self.$Modal.success({
		                                 title: '',
		                                 content: '操作成功'
		                             });
		                         }else if(data.returnCode == "1"){
		                        	 // 不作处理
		                         }else if(data.returnCode == "9996"){
		                        	// 轮询结束
		                        	 clearInterval(interval);
		                        	 layer.close(loadingIndex);
		                             self.toLoading();
		                             self.uploadSalaryModel = false;
		                             self.$refs.upload.clearFiles();
		                             self.uploadSalarySetForm.uploadSalaryFile = null;
		                             self.$Modal.error({content: '消息：' + data.msg});
		                         }else{
		                        	// 轮询结束
		                        	 clearInterval(interval);
		                        	 layer.close(loadingIndex);
		                             self.uploadSalaryModel = false;
		                             self.$refs.upload.clearFiles();
		                             self.uploadSalarySetForm.uploadSalaryFile = null;
		                             self.$Modal.error({content: '消息：' + data.msg});
		                             self.toLoading();
		                         }
		                  	},
		                    error:function (data) {
		                    	 console.log("错误轮询", arguments);
		                    	// 轮询结束
	                        	 clearInterval(interval);
	                        	 layer.close(loadingIndex);
	                             self.uploadSalaryModel = false;
	                             self.$refs.upload.clearFiles();
	                             self.uploadSalarySetForm.uploadSalaryFile = null;
	                             self.$Modal.error({content: '消息：' + data.msg});
	                             self.toLoading();
		                    }
		                  })
                  }, 2000);
            },
            
            dataCheck:function (fileId,batchCode,templateCode) {
                var self = this;
                var url = basePath + "dataImport/updataCheckState?fileId="+fileId+"&batchCode="+batchCode+"&templateCode="+templateCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            //修改审核状态
                            layer.msg('审核成功');
                            self.toLoading();
                        }else {
                            layer.msg('审核失败：'+result.msg);
                        }
                    },
                    error:function (result) {
                        layer.msg('审核失败：'+result.msg);
                    }
                });
            }


        },
        mounted:function(){
            this.init();
        }
    });
});
//














